package com.zjmzxfzhl.modules.app.controller;

import java.util.*;

import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.zjmzxfzhl.common.core.exception.SysException;
import com.zjmzxfzhl.common.core.util.SecurityUtils;
import com.zjmzxfzhl.modules.app.entity.*;
import com.zjmzxfzhl.modules.app.form.AppProjVo;
import com.zjmzxfzhl.modules.app.form.DocFilePath;
import com.zjmzxfzhl.modules.app.form.ProjSumVo;
import com.zjmzxfzhl.modules.app.platform.MailinaboxMailUtils;
import com.zjmzxfzhl.modules.app.platform.MailinaboxUserUtils;
import com.zjmzxfzhl.modules.app.service.AppMptService;
import com.zjmzxfzhl.modules.app.service.AppTaskService;
import com.zjmzxfzhl.modules.sys.entity.vo.ElTree;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjmzxfzhl.common.core.Result;
import com.zjmzxfzhl.common.core.base.BaseController;
import com.zjmzxfzhl.modules.app.entity.AppProj;
import com.zjmzxfzhl.modules.app.service.AppProjService;

/**
 * Controller
 * 
 * @author 张森荣
 */
@RestController
@RequestMapping("/app/proj")
public class AppProjController extends BaseController {

    @Autowired
    private AppProjService appProjService;
    @Autowired
    private AppTaskService appTaskService;
    @Autowired
    private AppMptService appMptService;

    @Value("${mailinabox.postfix}")
    private  String postfix; //邮箱后缀

    @Autowired
    private MailinaboxUserUtils mailinaboxUserUtils;

    @Autowired
    private MailinaboxMailUtils mailinaboxMailUtils;

    /**
     * 自定义查询列表
     * 
     * @param appProj
     * @param current
     * @param size
     * @param isMaster 查看我负责的项目（0:全部项目,1:我负责的项目）
     * @return
     */
//    @PreAuthorize("@elp.single('app:proj:list')")
    @GetMapping(value = "/list")
    public Result list(AppProjVo appProj, @RequestParam Integer current, @RequestParam Integer size,Integer isMaster) {
        if (isMaster != null && isMaster == 1) {
            String userId = SecurityUtils.getUserId();
            if(userId==null){
                return Result.error("找不到用户");
            }
            appProj.setMasterUserId(userId);
        }

        //不为超级管理员只能查看我参与的项目
        String userId = SecurityUtils.getUserId();
        if(!"admin".equals(userId)){
            appProj.setMyProj(userId);
        }
        IPage<AppProj> pageList = appProjService.list(new Page<AppProj>(current, size), appProj);

        List<AppProj> projList=pageList.getRecords();
        List<AppProjVo> projVoList=new ArrayList<>();
        for (AppProj proj :projList) {
            AppProjVo appProjVo=new AppProjVo();
            BeanUtils.copyProperties(proj,appProjVo);
            //计算任务数
            Integer taskNum = appTaskService.count(new LambdaQueryWrapper<AppTask>().eq(AppTask::getProjId, proj.getProjId()));
            appProjVo.setTaskNum(taskNum);
            //计算里程碑数
            Integer mptNum = appMptService.count(new LambdaQueryWrapper<AppMpt>().eq(AppMpt::getProjId, proj.getProjId()));
            appProjVo.setMptNum(mptNum);

            projVoList.add(appProjVo);
        }
        IPage<AppProjVo> voIPage=new Page<>();
        BeanUtils.copyProperties(pageList,voIPage);
        voIPage.setRecords(projVoList);
        return Result.ok(voIPage);
    }

//    @PreAuthorize("@elp.single('app:proj:list')")
    @GetMapping(value = "/queryById")
    public Result queryById(@RequestParam String id) {
        AppProj appProj = appProjService.queryById(id);
        return Result.ok(appProj);
    }

    /**
     * @功能：新增
     * @param appProj
     * @return
     */
//    @PreAuthorize("@elp.single('app:proj:save')")
    @PostMapping(value = "/save")
    public Result save(@Valid @RequestBody AppProj appProj) {
        if("".equals(appProj.getProjSn())){
            return Result.error("项目编号不能为空");
        }
        Integer num = appProjService.count(new LambdaQueryWrapper<AppProj>().eq(AppProj::getProjSn, appProj.getProjSn()));
        if(num>0){
            return Result.error("项目编号重复");
        }
        appProjService.saveAppProj(appProj);
        return Result.ok();
    }

    /**
     * @功能：修改
     * @param appProj
     * @return
     */
//    @PreAuthorize("@elp.single('app:proj:update')")
    @PutMapping(value = "/update")
    public Result update(@Valid @RequestBody AppProj appProj) {
        appProj.setParentProjId(null);
        appProj.setProjLevel(null);
        appProj.setProjLevelCode(null);
        appProj.setIsLeaf(null);
        appProj.setStatus(null);

        AppProj proj=appProjService.queryById(appProj.getProjId());
        //超级管理员可直接修改项目
        String userId = SecurityUtils.getUserId();
        if(!"admin".equals(userId)) {
            if (!"1".equals(proj.getRevise())) {
                return Result.error("项目当前不可修改");
            }
        }

        appProjService.updateAppProj(appProj);
        return Result.ok();
    }

    /**
     * @功能：批量删除
     * @param ids
     * @return
     */
//    @PreAuthorize("@elp.single('app:proj:delete')")
    @DeleteMapping(value = "/delete")
    public Result delete(@RequestParam String ids) {
        if (ids == null || ids.trim().length() == 0) {
            return Result.error("ids can't be empty");
        }
        Boolean result=appProjService.delByIds(ids);
        if(result==false){
            return Result.error("检查目录下是否存在未删除子项目！");
        }

        return Result.ok();
    }

    /**
     *
     * @param current 页数（根节点查询使用）
     * @param size 大小（根节点查询使用）
     * @param parentId 父节点（无法与分页，查询条件混用）
     * @param level 展开层级（无法与分页，查询条件混用）
     * @param appProj 查询条件
     * @param isMyMaster 查看我负责的项目（0:全部项目,1:我负责的项目）
     * @param isUpdate 查看最近修改的项目（0:全部项目,1:最近修改的项目）
     * @return total字段只在根节点查询有效
     */
//    @PreAuthorize("@elp.single('app:Proj:list')")
    @GetMapping(value = "/getTreeData")
    public Result getSelectTreeData(AppProjVo appProj,Integer current,Integer size,String parentId,Integer level,Integer isMyMaster, Integer isUpdate) {
        // 默认返回当前用户数据权限范围的机构树
        Map<String,Object> resultMap=new HashMap();

        if (isMyMaster != null && isMyMaster == 1) {
            String userId = SecurityUtils.getUserId();
            if(userId==null){
                return Result.error("找不到用户");
            }
            appProj.setMasterUserId(userId);
        }
        if (isUpdate != null && isUpdate == 1) {
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(new Date());
            calendar.add(calendar.DATE,-7);
            appProj.setUpdateTime(calendar.getTime());
        }
        //不为超级管理员只能查看我参与的项目
        String userId = SecurityUtils.getUserId();
        if(!"admin".equals(userId)){
            appProj.setMyProj(userId);
        }

        List<ElTree> treeData = appProjService.getTreeData(appProj,current,size,parentId,level);
        resultMap.put("data",treeData);

        Integer total=appProjService.selectRowCount(appProj);
        resultMap.put("total",total);

        return Result.ok(resultMap);
    }

    /**
     * @功能：移动树
     * @param id 节点id
     * @param parentId 原父id
     * @param newParentId 目标父id
     * @return
     */
    @PreAuthorize("@elp.single('app:Dir:update')")
    @PutMapping(value = "/moveTree")
    public Result moveTree(@RequestParam String id,@RequestParam String parentId,@RequestParam String newParentId) {
        AppProj appProj=appProjService.getById(id);
        if(appProj==null){
            return Result.error("未找到结点");
        }
        appProj.setParentProjId(newParentId);
        appProjService.moveTree(appProj,parentId);

        return Result.ok();
    }
    /**
     * @功能： 状态变更{00.待办的,01.进行中,02.已完成,03.已终止,04.已中止}
     * @param projId
     * @param status
     * @return
     */
//    @PreAuthorize("@elp.single('app:task:update')")
    @PutMapping(value = "/projChange")
    public Result projChange(@RequestParam String projId,@RequestParam String status) {
        Boolean result =true;
        switch (status) {
            case "00": //待办的
                result =appProjService.wait(projId);
                break;
            case "01": //进行中
                result =appProjService.inProgress(projId);
                break;
            case "02": //已完成
                result =appProjService.finish(projId);
                break;
            case "03": //已终止
                result =appProjService.close(projId);
                break;
            case "04": //已中止
                result =appProjService.suspend(projId);
                break;
            default: return Result.error("查找任务状态失败！");
        }
        if(result==false){
            return Result.error("任务状态更改失败！");
        }
        return Result.ok();
    }

    /**
     * 统计项目概括
     *
     * @return
     */
    //    @PreAuthorize("@elp.single('app:proj:list')")
    @GetMapping(value = "/summarize")
    public Result summarize() {
        String userId = SecurityUtils.getUserId();
        if (userId == null) {
            return Result.error("找不到用户");
        }
        ProjSumVo projSumVo = appProjService.getProjSun(userId);
        return Result.ok(projSumVo);
    }

    /**
     * 纪要检索项目
     *
     * @return
     */
    //    @PreAuthorize("@elp.single('app:proj:list')")
    @GetMapping(value = "/getMeetProj")
    public Result getMeetProj(String projIds) {
        if(projIds==null){
            return Result.error("请先选项目");
        }
        String[] idsArr = projIds.split(",");
        List<AppProj> projSumVo = appProjService.getMeetProj(idsArr);
        return Result.ok(projSumVo);
    }

    /**
     * 使用模板
     *
     * @return
     */
    //    @PreAuthorize("@elp.single('app:proj:list')")
    @GetMapping(value = "/useTemplate")
    public Result useTemplate(String projId,String dirId) {
        if(projId==null){
            return Result.error("请先选项目");
        }
        if(dirId==null){
            return Result.error("请先选要使用的模板");
        }
        appProjService.useTemplate(projId,dirId);
        return Result.ok();
    }

    /**
     * 接收邮箱
     *
     * @return
     */
    //    @PreAuthorize("@elp.single('app:proj:list')")

    @GetMapping(value = "/getEmail")
    public Result getEmail() {

        String mailbox= "test1@pm.redphase.net";

        try {
            String str = mailinaboxUserUtils.addUsers(mailbox, "1234567890", "");

            if (!"mail user added\n".equals(str)) {
                if ("User already exists.".equals(str)) {
                    throw new SysException("电子邮件已存在！请修改项目编号！");
                }
                if ("Invalid email address.".equals(str)) {
                    throw new SysException("无效的电子邮件地址！请修改项目编号！");
                }
                throw new SysException(str);
            }
        } catch (Exception e) {

        }

        try {
            mailinaboxMailUtils.getMail("test1@pm.redphase.net","1234567890",null,null);
        } catch (Exception e) {
            Result.error(e.getMessage());
        }

        return Result.ok();

    }

    /**
     * 删除邮箱
     *
     * @return
     */
    //    @PreAuthorize("@elp.single('app:proj:list')")
    @GetMapping(value = "/delEmail")
    public Result delEmail() {

        try {
            mailinaboxUserUtils.addRemove("333@mail.joyoc.com");
        } catch (Exception e) {

        }

        try {
            mailinaboxUserUtils.addRemove("3333@mail.joyoc.com");
        } catch (Exception e) {

        }

        try {
            mailinaboxUserUtils.addRemove("2222@mail.joyoc.com");
        } catch (Exception e) {

        }

        try {
            mailinaboxUserUtils.addRemove("111233444@mail.joyoc.com");
        } catch (Exception e) {

        }


        try {
            mailinaboxUserUtils.addRemove("1111@mail.joyoc.com");
        } catch (Exception e) {

        }


        try {
            mailinaboxUserUtils.addRemove("001@mail.joyoc.com");
        } catch (Exception e) {

        }

        try {
            mailinaboxUserUtils.addRemove("test@pm.redphase.net");
        } catch (Exception e) {

        }

        try {
            mailinaboxUserUtils.addRemove("test1@pm.redphase.net");
        } catch (Exception e) {

        }

        return Result.ok();

    }


    /**
     * 测试邮箱
     *
     * @return
     */
    //    @PreAuthorize("@elp.single('app:proj:list')")
    @GetMapping(value = "/testEmail")
    public Result testEmail() {

//        String password = UUID.randomUUID().toString().replace("-", "").toLowerCase();
//
//        IPage<AppProj> pageList = appProjService.list(new Page<AppProj>(1, 1000), null);
//
//        List<AppProj> projList=pageList.getRecords();
//        for (AppProj proj :projList) {
//            //创建邮箱
//            try {
//                String mailbox=proj.getProjSn()+"@"+postfix;
//                proj.setMailbox(mailbox);
//                proj.setMailPassword(password);
//
//                String str = mailinaboxUserUtils.addUsers(proj.getMailbox(), password, "");
//                if (!"mail user added\n".equals(str)) {
//                    if ("User already exists.".equals(str)) {
//                        throw new SysException("电子邮件已存在！请修改项目编号！");
//                    }
//                    if ("Invalid email address.".equals(str)) {
//                        throw new SysException("无效的电子邮件地址！请修改项目编号！");
//                    }
//                    throw new SysException(str);
//                }
//                appProjService.updateById(proj);
//            } catch (Exception e) {
//                System.out.println(e.getMessage());
//            }
//        }

        return Result.ok();
    }
}
